package com.siro.auth.utils;

import com.siro.auth.base.constant.ResultCode;
import com.siro.auth.base.exception.ServiceException;
import com.siro.auth.base.common.model.LoginUser;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全服务工具类
 *
 * @author starsea
 * @date 2022-07-25 10:34
 */
public class SecurityUtils {

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException("获取用户信息异常", ResultCode.UNAUTHORIZED);
        }
    }

    /**
     * 获取登录用户id
     */
    public static Long getUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取登录部门id
     */
    public static Long getDeptId() {
        return getLoginUser().getDeptId();
    }

    /**
     * 获取登录用户名
     */
    public static String getUsername() {
        return getLoginUser().getUsername();
    }
}
